package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String SSOServerUrl;

    // 无需认证就可以访问
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }


    // 需要认证才可以访问
    @GetMapping("/employees")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token",required = false) String token){

        if(!StringUtils.isEmpty(token)) {
            // TODO 去认证中心查询用户的信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> entity = restTemplate.getForEntity("http://ssoserver.com:8090/userInfo?token=" + token, String.class);
            String body = entity.getBody();
            session.setAttribute("loginUser", body);
        }

        Object user = session.getAttribute("loginUser");
        if(user==null){
            // 没有认证,需要去认证
            // 当认证中心认证完成之后，让认证中心知道你要跳转回的地址？解决方案就是在请求参数中携带跳转回的地址
            return "redirect:"+SSOServerUrl+"?redirect_url=http://client1.com:8091/employees";
        }else{
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            emps.add("王五");
            model.addAttribute("emps",emps);
            return "list";
        }
    }

}
